package cmd

import (
	"biz_alert/config"
	"biz_alert/controller"
	"biz_alert/pkg/db"
	"github.com/spf13/cobra"
	"go.uber.org/zap"
)

func init() {
	RootCmd.AddCommand(AlertCmd())
}

func AlertCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "alert",
		Short: "业务告警",
		Long:  "启动业务告警程序",
		RunE: func(cmd *cobra.Command, args []string) error {
			tasks := []func(config config.Config) error{
				SetupGlobalDB,
			}
			for _, task := range tasks {
				if err := task(*config.C); err != nil {
					zap.L().Panic("setup failed", zap.Error(err))
					return err
				}
			}
			svr := controller.NewBizExceptionControllerImpl(db.GlobalDB)
			message, err := svr.GetBizException()
			err = svr.SendMessageToWechat(config.C.AlertChannel.Wechat.Webhook, message)
			if err != nil {
				return err
			}
			return nil
		},
		PreRunE: func(cmd *cobra.Command, args []string) error {
			return config.LoadCongFromToml(cfgFile)
		},
	}
	cmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "config.toml", "配置文件目录")
	return cmd
}
